import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useDictStoreHook } from "@/store/modules/dict";
import {
  ElLoading,
  ElMessage,
  ElMessageBox,
  ElNotification,
} from "element-plus";
import Cookies from "js-cookie";
import router from "@/router";
import { getStore, getToken, setStore } from "@/utils/auth";
import { isRelogin } from "@/utils/request";
const useUserStore = useUserStoreHook();
const permissionStore = usePermissionStoreHook();
const dictStore = useDictStoreHook();
// 轻量级的进度条组件
NProgress.configure({ showSpinner: false });
const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];

// 路由循环执行直到遇到相匹配(路由命中)的路由后跳转、否则会一直循环寻找路由
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (getToken()) {
    to.meta.title;
    if (to.path === "/login") {
      // 设置系统登陆后默认折叠左侧菜单栏
      Cookies.set("sidebarStatus", String(0));
      next({ path: "/" });
      NProgress.done();
    } else {
      if (useUserStore.user.roles.length === 0) {
        isRelogin.show = true;
        // 判断当前用户是否已拉取完user_info信息
        await useUserStore
          .GetInfo()
          .then(() => {
            isRelogin.show = false;
            const defaultRoleGroupId = getStore({
              // @ts-ignore
              name: "roleGroupId" + "-" + useUserStore.user.userInfo.userId,
            });
            let roleGroupId = "";
            if (!defaultRoleGroupId) {
              // 获取用户所选服务第一条
              roleGroupId =
                useUserStore.user.sysRoleGroup.length > 0
                  ? // @ts-ignore
                    useUserStore.user.sysRoleGroup[0].roleGroupId
                  : "";
            } else {
              roleGroupId = defaultRoleGroupId;
            }
          })
          .catch((err) => {
            useUserStore.LogOut().then(() => {
              ElMessage.error(err);
              next({ path: "/" });
            });
          });
        /** 获取系统字典 */
        const dictDataAllList = await dictStore.getDataList();
        setStore({ name: "dictDataAll-list", content: dictDataAllList });
        /** 获取权限路由 */
        const accessRoutes: any = await permissionStore.GenerateRoutes("");
        const accessRoutesList: any = toRaw(accessRoutes.value);
        // 根据roles权限生成可访问的路由表
        // @ts-ignore
        accessRoutesList.forEach((route) => {
          router.addRoute(route);
        });
        next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
      } else {
        // 未匹配到任何路由，跳转404  防止出现路由不存在，页面报警告信息
        if (to.matched.length === 0) {
          from.name ? next({ name: from.name }) : next("/404");
        } else {
          next();
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
